/**
 * 文件处理工具类
 */
export const fileTools = {
  /**
   * 加载默认视频
   * @param {string} videoPath 视频路径
   * @returns {Promise<File>} 视频文件
   */
  async loadDefaultVideo(videoPath) {
    try {
      const response = await fetch(videoPath);
      const blob = await response.blob();
      return new File([blob], 'default.mp4', { type: 'video/mp4' });
    } catch (error) {
      console.error('加载默认视频失败:', error);
      throw error;
    }
  },
  
  /**
   * 导出帧为ZIP文件
   * @param {Array} frames 帧数据URL数组
   * @param {Function} statusCallback 状态回调函数
   */
  async exportFramesAsZip(frames, statusCallback) {
    statusCallback("正在打包帧...");

    try {
      const JSZip = (await import('https://cdn.jsdelivr.net/npm/jszip@3.10.1/+esm')).default;
      const zip = new JSZip();
      
      const timer = Date.now();
      // 分块处理避免内存溢出
      const chunkSize = 100;
      for (let i = 0; i < frames.length; i += chunkSize) {
        const chunk = frames.slice(i, i + chunkSize);
        chunk.forEach((dataURL, index) => {
          const base64 = dataURL.split(',')[1];
          zip.file(timer + `_${(i + index).toString().padStart(4, '0')}.png`, base64, { base64: true });
        });
        await new Promise(r => setTimeout(r, 0));
        statusCallback(`正在打包: ${Math.min(i + chunkSize, frames.length)}/${frames.length} 帧`);
      }

      statusCallback("正在生成ZIP文件...");
      const blob = await zip.generateAsync({ type: 'blob' });
      const url = URL.createObjectURL(blob);

      const a = document.createElement('a');
      a.href = url;
      a.download = 'frames.zip';
      a.click();

      return true;
    } catch (error) {
      console.error('导出帧时出错:', error);
      throw error;
    }
  }
};